#include "MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    mdiArea = new QMdiArea;
    mdiArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    mdiArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setCentralWidget(mdiArea);
    windowMapper = new QSignalMapper(this);
    connect(windowMapper, SIGNAL(mapped(QWidget*)), this, SLOT(setActiveSubWindow(QWidget*)));
    fileMenu = menuBar()->addMenu(tr("&File"));
    QAction *newAct = new QAction(tr("ConfigureWidget"), this);
    fileMenu->addAction(newAct);
    connect(newAct, SIGNAL(triggered()), this, SLOT(addconifg()));
    statusBar()->showMessage(tr("Ready"));
    windowMenu = menuBar()->addMenu(tr("&Window"));
    connect(windowMenu, SIGNAL(aboutToShow()), this, SLOT(updateWindowMenu()));
}

MainWindow::~MainWindow()
{
}
void MainWindow::addconifg()
{
    ConfigureWidget *cw = new ConfigureWidget;
    mdiArea->addSubWindow(cw);
    cw->show();
}
void MainWindow::updateWindowMenu()
{
    windowMenu->clear();
    QList<QMdiSubWindow *> windows = mdiArea->subWindowList();

    for(int i = 0; i < windows.size(); ++i)
    {
        MdiChild *child = qobject_cast<MdiChild *>(windows.at(i)->widget());
        QAction *action  = windowMenu->addAction(child->windowTitle());
        action->setCheckable(true);
        action ->setChecked(child == activeMdiChild());
        connect(action, SIGNAL(triggered()), windowMapper, SLOT(map()));
        windowMapper->setMapping(action, windows.at(i));
    }
}
MdiChild *MainWindow::activeMdiChild()
{
    if(QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())
        return qobject_cast<MdiChild *>(activeSubWindow->widget());

    return 0;
}
void MainWindow::closeEvent(QCloseEvent *event)
{
    mdiArea->closeAllSubWindows();

    if(mdiArea->currentSubWindow())
    {
        event->ignore();
    }
    else
    {
        event->accept();
    }
}
void MainWindow::setActiveSubWindow(QWidget *window)
{
    if(!window)
        return;

    mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow *>(window));
}